package struct.tree.iter;

import struct.tree.node.Node;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: 柒月
 * @date: 2025/5/3 下午10:17
 * @version: 1.0
 */
public class PosorderTraversal {

    public static int[] posrderRecursion(Node root) {
        List<Integer> list = new LinkedList<>();
        posrderRecursion(root, list);
        return list.stream().mapToInt(i -> i).toArray();
    }

    private static void posrderRecursion(Node root, List<Integer> list) {
        if (root == null) return;
        posrderRecursion(root.left, list);
        posrderRecursion(root.right, list);
        list.add(root.data);
    }

    public static int[] posrderIteration(Node root) {
        Deque<Node> stack = new LinkedList<>();
        List<Integer> list =  new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node h = stack.peek();
            if (h.left != null && h.left != root && h.right != root) {
                stack.push(h.left);
            } else if (h.right != null && h.right != root) {
                stack.push(h.right);
            } else {
                Node node = stack.pop();
                list.add(node.data);
                root = node;
            }
        }
        return list.stream().mapToInt(i -> i).toArray();
    }

    public static int[] posrderIterationTwoStack(Node root) {
        List<Integer> list = new LinkedList<>();
        Deque<Node> stack = new LinkedList<>();
        Deque<Node> result = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            result.push(node);
            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        while (!result.isEmpty()) {
            list.add(result.pop().data);
        }
        return list.stream().mapToInt(i -> i).toArray();
    }
}
